// 实现这个项目的构建任务

const { src, dest, series, parallel, watch } = require('gulp')
const del = require('del')
const browserSync = require('browser-sync')

const loadPlugins = require('gulp-load-plugins')

const plugins = loadPlugins()
const browserServer = browserSync.create()
// 样式转换
const style = () => {
  return src('src/assets/styles/*.scss', {base: 'src'})
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('.temp'))
}

// js编译
const script = () => {
  return src('src/assets/scripts/*.js', {base: 'src'})
    .pipe(plugins.babel({presets: ['@babel/preset-env']}))
    .pipe(dest('.temp'))
}

// html编译
const data = {
  pkg: require('./package.json'),
  date: new Date(),
}
const html = () => {
  return src('src/*.html', {base: 'src'})
    .pipe(plugins.swig({ data, defaults: {cache: false} }))
    .pipe(dest('.temp'))
}

// 图片转换
const image = () => {
  return src('src/assets/images/**', {base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 字体
const font = () => {
  return src('src/assets/fonts/**', {base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 其他文件
const extra = () => {
  return src('public/**', {base: 'public'})
    .pipe(dest('dist'))
}

// 清除
const clean = () => {
  return del(['dist', '.temp'])
}

// server
const server = () => {

  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', html)

  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**',
  ], browserServer.reload)

  browserServer.init({
    notify: false,
    files: '.temp/**',
    server: {
      baseDir: ['.temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

// 引用依赖
const useref = () => {
  return src('.temp/*.html', {base: '.temp'})
    .pipe(plugins.useref({searchPath: ['.temp', '.']}))
    // 压缩代码
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({collapseWhitespace: true, minifyCSS: true, minifyJS: true})))
    .pipe(dest('dist'))
}

// 编译
const compile = parallel(style, script, html)
// 打包
const build = series(clean, parallel(series(compile, useref), image, font, extra))
// 开发
const dev = series(compile, server)

module.exports = {
  build,
  clean,
  dev,
}